import {Component, OnInit} from '@angular/core';
import {from} from 'rxjs';
import {DBService} from './db/db.service';
import {PyodideService} from './pyodide/pyodide.service';
import {CourseLoaderService} from './course/course-loader.service';
import {filter} from 'rxjs/operators';
import {NzModalService} from 'ng-zorro-antd/modal';
import {CookieService} from 'ngx-cookie';

@Component({selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})
export class AppComponent implements OnInit {
    constructor(private pyodide : PyodideService, private dbService : DBService, private courseLoader : CourseLoaderService, private modal : NzModalService, private cookie : CookieService, private window: Window) {}
    persistent : boolean = false;
    ngOnInit(): void {
        navigator.permissions.query({name: "persistent-storage"}).then((result) => {
            if (result.state === 'granted') {
                this.persistent = true;
            } else if (result.state === 'prompt') {
                if (!this.cookie.hasKey('permission-prompt')) {
                    this.cookie.put('permission-prompt', 'done');
                    this.modal.info({
                        nzTitle: '申请持久化存储权限',
                        nzContent: '如果您需要长时间保留本站数据，避免被浏览器自动清理策略清除，请在之后的申请窗口中允许授予权限<br/>如果你的浏览器基于Chromium，可能会申请通知权限（但本网站保证不会发送通知），因为Chromium并未直接开放持久存储申请权限<br/>根据浏览器的设置，也可能没有弹出窗口，此时无需介意，之后注意定时备份即可',
                        nzOnOk: () => {
                            // chromium
                            if((this.window as any).chrome){
                                Notification.requestPermission( status => {
                                    if(status === "granted"){
                                        navigator.storage.persist().then((persistent) => {
                                            this.persistent = persistent;
                                        });
                                    }
                                });
                            }else{
                                navigator.storage.persist().then((persistent) => {
                                    this.persistent = persistent;
                                });
                            }
                        }
                    })
                }
            } else if (result.state === 'denied') {}
        });
        this.pyodide.load().subscribe(
        // p=> alert(this.pyodide.runSync('1+2'))
        );
        this.dbService.connect();
    }
}
